const Controller = require('egg').Controller;
const bcrypt = require('bcryptjs');

class UserController extends Controller {
  // 注册接口
  async register() {
    const { ctx } = this;
    const result = await this.service.user.register();
    if (result.affectedRows === 1) {
      ctx.body = { success: true, message: 'User registered successfully.' };
    } else {
      ctx.body = { success: false, message: 'Registration failed.' };
    }
  }
  async create() {
    const { ctx } = this;
    const result = await this.service.user.create();
    if (result.affectedRows === 1) {
      ctx.body = { success: true, message: 'User registered successfully.' };
    } else {
      ctx.body = { success: false, message: 'Registration failed.' };
    }
  }

  // 登录接口
  async login() {
    const { ctx } = this;
    const { phone_number, password, avatar, gender, age, birthplace, residence, occupation, medical_history, role } = ctx.request.body;
    const user = await this.service.user.login();
    if (user && bcrypt.compareSync(password, user.password)) {
      ctx.body = { success: true, message: 'Login successful.', user: { phone_number, role: user.role ,id:user.id} };
    } else {
      ctx.body = { success: false, message: 'Invalid phone number or password.' };
    }
  }

  // 获取所有用户
  async list() {
    const { ctx } = this;
    // console.log(this.service.user.list);
    const users = await this.service.user.list();
    ctx.body = { success: true, data: users };
  }

  // 获取单个用户
  async read() {
    const { ctx } = this;
    const user = await this.service.user.read();
    if (user) {
      ctx.body = { success: true, data: user };
    } else {
      ctx.body = { success: false, message: 'User not found.' };
    }
  }

  async listDoctors() {
    const { ctx } = this;
    const doctors = await this.service.user.listDoctors();
    if (doctors.length > 0) {
      ctx.body = { success: true, data: doctors };
    } else {
      ctx.body = { success: false, message: 'No doctors found.' };
    }
  }
  

  // 更新用户信息
  async update() {
    const { ctx } = this;
    const result = await this.service.user.update();
    if (result.affectedRows === 1) {
      ctx.body = { success: true, message: 'User updated successfully.' };
    } else {
      ctx.body = { success: false, message: 'Update failed.' };
    }
  }

  // 删除用户
  async delete() {
    const { ctx } = this;
    const result = await this.service.user.delete();
    if (result.affectedRows === 1) {
      ctx.body = { success: true, message: 'User deleted successfully.' };
    } else {
      ctx.body = { success: false, message: 'Deletion failed.' };
    }
  }
}

module.exports = UserController;
